﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;

namespace MyGIS.Forms
{
    public partial class KernelDensityForm : Form
    {
        private AxMapControl mapControl;
        // 公共属性用于传递参数
        public string InputFeatureLayer { get; private set; }
        public string PopulationField { get; private set; }
        public string OutputRasterPath { get; private set; }
        public double CellSize { get; private set; }
        public double SearchRadius { get; private set; }
        public esriAreaUnits AreaUnitScaleFactor { get; private set; }

        public KernelDensityForm(AxMapControl mapControl)
        {
            InitializeComponent();
            this.mapControl = mapControl;
            InitializeForm();
        }

        private void InitializeForm()
        {
            // 初始化窗体控件
            this.Text = "核密度分析参数设置";
            this.StartPosition = FormStartPosition.CenterParent;

            // 初始化单位组合框
            comboBoxUnits.Items.Add("平方千米");
            comboBoxUnits.Items.Add("公顷");
            comboBoxUnits.Items.Add("平方米");
            comboBoxUnits.SelectedIndex = 0; // 默认平方千米

            // 填充地图中的点图层
            for (int i = 0; i < mapControl.LayerCount; i++)
            {
                IFeatureLayer featureLayer = mapControl.get_Layer(i) as IFeatureLayer;
                if (featureLayer != null && featureLayer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPoint)
                {
                    comboBoxLayers.Items.Add(featureLayer.Name);
                }
            }

            // 设置默认值
            if (comboBoxLayers.Items.Count > 0)
            {
                comboBoxLayers.SelectedIndex = 0;
                // 手动触发一次字段填充
                comboBoxLayers_SelectedIndexChanged(comboBoxLayers, EventArgs.Empty);
            }

            textBoxCellSize.Text = "100"; // 默认像元大小
            textBoxSearchRadius.Text = "1000"; // 默认搜索半径
        }

        // 根据图层名获取图层对象
        private IFeatureLayer GetLayerByName(string layerName)
        {
            for (int i = 0; i < mapControl.LayerCount; i++)
            {
                if (mapControl.get_Layer(i).Name == layerName)
                {
                    return mapControl.get_Layer(i) as IFeatureLayer;
                }
            }
            return null;
        }

        private void buttonBrowse_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "TIFF文件|*.tif|所有文件|*.*";
            saveDialog.Title = "选择输出栅格文件";

            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                textBoxOutput.Text = saveDialog.FileName;
            }
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            // 验证输入
            if (comboBoxLayers.SelectedItem == null)
            {
                MessageBox.Show("请选择输入图层！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (string.IsNullOrEmpty(textBoxOutput.Text))
            {
                MessageBox.Show("请指定输出文件路径！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // 获取选中的图层
            IFeatureLayer featureLayer = GetLayerByName(comboBoxLayers.SelectedItem.ToString());
            if (featureLayer == null)
            {
                MessageBox.Show("无法找到指定的图层", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            // 设置属性值
            InputFeatureLayer = featureLayer.Name;
            PopulationField = comboBoxPopulationField.SelectedItem?.ToString() == "NONE"
                ? string.Empty
                : comboBoxPopulationField.SelectedItem?.ToString();
            OutputRasterPath = textBoxOutput.Text;

            // 验证像元大小
            if (!double.TryParse(textBoxCellSize.Text, out double cellSize) || cellSize <= 0)
            {
                MessageBox.Show("请输入有效的像元大小！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                textBoxCellSize.Focus();
                textBoxCellSize.SelectAll();
                return;
            }
            CellSize = cellSize;

            // 验证搜索半径
            if (!double.TryParse(textBoxSearchRadius.Text, out double searchRadius) || searchRadius <= 0)
            {
                MessageBox.Show("请输入有效的搜索半径！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                textBoxSearchRadius.Focus();
                textBoxSearchRadius.SelectAll();
                return;
            }
            SearchRadius = searchRadius;

            AreaUnitScaleFactor = (esriAreaUnits)comboBoxUnits.SelectedIndex;

            DialogResult = DialogResult.OK;
            Close();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        // 图层选择变化事件
        private void comboBoxLayers_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBoxPopulationField.Items.Clear();

            if (comboBoxLayers.SelectedItem != null)
            {
                IFeatureLayer featureLayer = GetLayerByName(comboBoxLayers.SelectedItem.ToString());
                if (featureLayer != null)
                {
                    // 添加所有数值型字段
                    for (int i = 0; i < featureLayer.FeatureClass.Fields.FieldCount; i++)
                    {
                        IField field = featureLayer.FeatureClass.Fields.get_Field(i);
                        if (IsNumericField(field.Type))
                        {
                            comboBoxPopulationField.Items.Add(field.Name);
                        }
                    }

                    // 添加"NONE"选项
                    comboBoxPopulationField.Items.Add("NONE");

                    if (comboBoxPopulationField.Items.Count > 0)
                        comboBoxPopulationField.SelectedIndex = 0;
                }
            }
        }

        // 检查字段是否为数值型
        private bool IsNumericField(esriFieldType fieldType)
        {
            return fieldType == esriFieldType.esriFieldTypeDouble ||
                   fieldType == esriFieldType.esriFieldTypeInteger ||
                   fieldType == esriFieldType.esriFieldTypeSingle ||
                   fieldType == esriFieldType.esriFieldTypeSmallInteger;
        }
    }
}